package com.example.system.security.service;

import com.example.system.security.model.LoginUserDetails;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.example.common.entity.SysUser;

import java.util.List;

/**
 * 根据用户名查询用户信息和权限
 */
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
    
    private final UserService userService;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在：" + username);
        }
        
        List<String> permissions = userService.getUserPermissions(user.getUserId());
        
        return new LoginUserDetails(
            user.getUserId(),
            user.getUsername(),
            user.getPassword(),
            user.isEnabled(),
            permissions
        );
    }
}
